package com.youlu.campus.service.ca.impl;

import com.youlu.campus.entity.CaOrganization;
import com.youlu.campus.entity.CaTemplate;
import com.youlu.campus.entity.VO.req.CaOrgReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.regex.Pattern;

@Slf4j
@Service
public class CaOrganizationService {

    @Autowired
    private MongoTemplate mongoTemplate;

    public void save(CaOrganization caOrganization){
        Date now = new Date();
        if(StringUtils.isEmpty(caOrganization.getId())){
            caOrganization.setCreatedTime(now);
        }else{
            CaOrganization organization = this.mongoTemplate.findById(caOrganization.getId(), CaOrganization.class);
            if(Objects.nonNull(organization)){
                caOrganization.setUpdatedTime(now);
                if(Objects.isNull(organization.getCreatedTime())){
                    caOrganization.setCreatedTime(now);
                }else{
                    caOrganization.setCreatedTime(organization.getCreatedTime());
                }

            }
        }
        this.mongoTemplate.save(caOrganization);
    }

    public Page<CaOrganization> list (CaOrgReq caOrgReq){
        String name = caOrgReq.getName();
        Query query = new Query();
        if(StringUtils.isNotBlank(name)){
            Pattern pattern = Pattern.compile("^.*" + name + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        PageRequest pageRequest = PageRequest.of(caOrgReq.getPage() - 1, caOrgReq.getPageSize());
        long count = this.mongoTemplate.count(query, CaOrganization.class);
        if(count==0){
            return PageableExecutionUtils.getPage(new ArrayList<>(), pageRequest, () -> 0);
        }
//        query.with(new Sort(Sort.Direction.DESC, "createdTime"));
        Sort sort=Sort.by(Sort.Direction.DESC, "createdTime");
        query.with(sort);
        List<CaOrganization> list = this.mongoTemplate.find(query.with(pageRequest), CaOrganization.class);
        return PageableExecutionUtils.getPage(list, pageRequest, () -> count);
    }
}
